package cn.yotta.user.core.server.iface.login.impl;

import cn.yotta.user.api.params.login.BaseLoginRequest;
import cn.yotta.user.core.server.dto.user.UserDto;
import cn.yotta.user.core.server.iface.login.LoginProvider;
import cn.yotta.user.web.autoconfiguration.exception.UserLoginException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author wyaoyao
 * @date 2023/3/9 17:46
 *
 */
@Component
public class LoginProviderManager {

    private final List<LoginProvider<? extends BaseLoginRequest>> providers;


    public LoginProviderManager(List<LoginProvider<? extends BaseLoginRequest>> providers) {
        this.providers = providers;
    }

    @SuppressWarnings({"rawtypes,unchecked"})
    public UserDto auth(BaseLoginRequest request) {
        UserDto user = null;
        for (LoginProvider loginProvider : providers) {
            if (loginProvider.support(request)) {
                user = loginProvider.auth(request);
                break;
            }
        }
        if (Objects.isNull(user)) {
            throw new UserLoginException("not support this login method");
        }
        return user;
    }
}
